clc
close all
clear all

img1 = imread('wadham001.pgm');
img2 = imread('wadham005.pgm');
img3 = [img1 img2];


source = [];
target = [];


figure
while true

    
subplot(2, 1, 1)
imshow(img3);
hold on


% visualise
for i = 1:size(source, 1)
    line = [source(i, :); target(i, :)];
    line(2, 1) = line(2, 1)+size(img1, 2);
    plot(line(:, 1), line(:, 2), 'Color', [1 0 0])
end
drawnow

% select source control points
source = [source; ginput(1)];

% select target control points
target = [target; ginput(1)];
target(end, 1) = target(end, 1)-size(img1, 2);


if size(source, 1) < 3
    continue;
end


% % compute mapping from target to source
% W = thinPlateSpline(target, source);
% 
% % sample points in target space and warp them to source space
% [X Y] = meshgrid(1:size(img1, 1), 1:size(img1, 2));
% new_points = thinPlateWarp([Y(:) X(:)], target, W);
% 
% % interpolate colour in source image and store them in target image
% newimage = zeros(size(img1));
% for i = 1:size(img1, 3)
%     newimage(:, :, i) = reshape(interp2(double(img1(:, :, i))/255, new_points(:, 1), new_points(:, 2), 'bilinear*'), size(img1, 2), size(img1, 1))';
% end

new_image = tpsWarp(target, source, img1);

img4 = [img1 uint8(new_image*255)];


% show new image
subplot(2, 1, 2)
imshow(img4)


end
